<template>
  <el-dialog title="添加部门" :visible.sync="showAdd" width="400px"
             @close="$emit('update:showAddDepartment', false)" :close-on-click-modal="false" @before-close="handleClose">
    <el-form label-position="right" ref="addInfo" :rules="rules" :model="addInfo" label-width="90px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="addInfo.name" @keyup.enter.native="$refs['remark'].focus()" ></el-input>
      </el-form-item>
      <el-form-item label="职能描述" prop="remark">
        <el-input ref="remark" v-model="addInfo.remark" type="textarea"
                  @keyup.enter.native="AddDepartment('addInfo')" :rows="4" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="closeModel">取 消</el-button>
        <el-button type="primary" @click="AddDepartment('addInfo')">确 定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
  export default {
    name: "AddDepartment",
    props: {
      showAddDepartment: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        showAdd: this.showAddDepartment,
        addInfo: {
          name: "",
          remark: ""
        },
        rules: {
          name: [
            {required: true, message: '请输入部门名称', trigger: 'blur'}
          ],
          remark: [
            {required: true, message: '请输入职能描述', trigger: 'blur'}
          ]
        }
      }
    },
    watch: {
      showAddDepartment() {
        this.showAdd = this.showAddDepartment
      }
    },
    methods: {
      handleClose(done) {
        this.resetForm()
        done()
      },
      closeModel() {
        this.resetForm()
        this.showAdd = false
      },
      resetForm() {
        this.$refs['addInfo'].resetFields();
      },
      AddDepartment(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            ajax.post(apis.auth.addDepartment, this.addInfo)
              .then(res => {
                if (res.success === true) {
                  this.$message({
                    message: res.message,
                    type: 'success'
                  });
                  this.addInfo = {
                    name: "",
                    remark: ""
                  }
                  this.showAdd = false
                  this.$emit("refreshDepartmentList")
                } else {
                  this.$message({
                    message: res.message,
                    type: 'error'
                  })
                }
              })
          }
          else {
            return false;
          }
        });
      }
    },
    created() {
    }
  }
</script>

<style lang="scss" scoped>
  .i-plus {
    text-align: center;
  }
</style>
